<template>
  <el-checkbox-group v-model="checked" v-bind="otherProps">
    <el-checkbox v-for="option in selectOptions" :key="option.value" :label="option.value">{{
        option.label
      }}
    </el-checkbox>
  </el-checkbox-group>
</template>

<script setup name="RCheckbox">

import {ref, watch} from "vue";
import {getDicts} from "@/api/system/dict/data";

const emit = defineEmits(['update:modelValue'])

const props = defineProps({
  modelValue: String,
  fieldProps: Object
})

const {optionType, options, dict, ...otherProps} = props.fieldProps

const checked = ref([])

const selectOptions = ref()

function getOptions() {
  if (optionType === 'custom') {
    selectOptions.value = options
  } else if (optionType === 'dict') {
    getDicts(dict).then(res => {
      const arr = []
      if (res.data) {
        res.data.forEach(dict => {
          arr.push({
            label: dict.dictLabel,
            value: dict.dictValue
          })
        })
        selectOptions.value = arr
      }
    })
  }
}

getOptions()

watch(() => props.modelValue, () => {
  if (!props.modelValue || props.modelValue === '') {
    checked.value = []
  } else {
    checked.value = props.modelValue.split(',')
  }
})

watch(() => checked, () => {
  if (checked.value.length) {
    emit("update:modelValue", checked.value.join(','))
  }
}, {deep: true})

</script>

<style scoped>

</style>
